"""
FastAPI集成示例
==============

演示如何在FastAPI应用中使用新的依赖注入系统。
"""

from fastapi import FastAPI, Depends, HTTPException, status
from typing import Dict, Any

from ..core.dependency_injection_new import (
    initialize_dependencies,
    get_dependency_manager,
    inject_cache_manager,
    inject_auth_service,
    perform_health_check
)
from ..interfaces.cache import AbstractCacheManager
from ..interfaces.auth import AbstractAuthService


# 创建FastAPI应用
def create_app(service_name: str = "example-service") -> FastAPI:
    """创建FastAPI应用实例"""
    
    app = FastAPI(
        title=f"RedFire {service_name}",
        description="使用新依赖注入系统的示例服务",
        version="1.0.0"
    )
    
    # 初始化依赖注入系统
    dependency_manager = initialize_dependencies(
        service_name=service_name,
        modules=[__name__]  # 连接当前模块
    )
    
    @app.on_event("startup")
    async def startup_event():
        """应用启动事件"""
        print(f"🚀 {service_name} 启动中...")
        print("✅ 依赖注入系统已初始化")
    
    @app.on_event("shutdown")
    async def shutdown_event():
        """应用关闭事件"""
        print(f"🛑 {service_name} 正在关闭...")
        # 清理依赖注入连接
        dependency_manager.unwire()
        print("✅ 依赖注入系统已清理")
    
    # 健康检查端点
    @app.get("/health")
    async def health_check():
        """健康检查端点"""
        health_result = await perform_health_check(service_name)
        
        if not health_result.get("healthy", False):
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail=health_result
            )
        
        return health_result
    
    # 缓存操作示例
    @app.get("/cache/test")
    async def test_cache(
        cache_manager: AbstractCacheManager = Depends(inject_cache_manager(service_name))
    ):
        """测试缓存操作"""
        
        # 设置缓存
        await cache_manager.set("test_key", "test_value", expire=60)
        
        # 获取缓存
        value = await cache_manager.get("test_key")
        
        # 检查存在性
        exists = await cache_manager.exists("test_key")
        
        # 获取TTL
        ttl = await cache_manager.ttl("test_key")
        
        return {
            "operation": "cache_test",
            "set_value": "test_value",
            "get_value": value,
            "exists": exists,
            "ttl": ttl
        }
    
    # 批量缓存操作示例
    @app.post("/cache/batch")
    async def batch_cache_operations(
        data: Dict[str, Any],
        cache_manager: AbstractCacheManager = Depends(inject_cache_manager(service_name))
    ):
        """批量缓存操作"""
        
        # 批量设置
        await cache_manager.mset(data, expire=300)
        
        # 批量获取
        keys = list(data.keys())
        values = await cache_manager.mget(keys)
        
        return {
            "operation": "batch_cache",
            "set_data": data,
            "get_data": values
        }
    
    # 认证相关示例
    @app.post("/auth/login")
    async def login(
        username: str,
        password: str,
        auth_service: AbstractAuthService = Depends(inject_auth_service(service_name))
    ):
        """用户登录示例"""
        
        # 用户认证
        user_data = await auth_service.authenticate_user(username, password)
        if not user_data:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
        
        # 创建访问令牌
        access_token = await auth_service.create_token(
            user_id=user_data["user_id"],
            user_data=user_data
        )
        
        # 创建刷新令牌
        refresh_token = await auth_service.create_refresh_token(
            user_id=user_data["user_id"]
        )
        
        # 创建会话
        session_id = await auth_service.create_session(
            user_id=user_data["user_id"],
            session_data={"login_time": "2025-01-09T12:00:00Z"}
        )
        
        return {
            "access_token": access_token,
            "refresh_token": refresh_token,
            "session_id": session_id,
            "user_data": user_data
        }
    
    @app.get("/auth/me")
    async def get_current_user(
        token: str,
        auth_service: AbstractAuthService = Depends(inject_auth_service(service_name))
    ):
        """获取当前用户信息"""
        
        user_data = await auth_service.get_current_user(token)
        if not user_data:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的令牌"
            )
        
        return user_data
    
    @app.post("/auth/refresh")
    async def refresh_token(
        refresh_token: str,
        auth_service: AbstractAuthService = Depends(inject_auth_service(service_name))
    ):
        """刷新访问令牌"""
        
        new_token = await auth_service.refresh_token(refresh_token)
        if not new_token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的刷新令牌"
            )
        
        return {"access_token": new_token}
    
    # 权限检查示例
    @app.get("/admin/data")
    async def get_admin_data(
        token: str,
        auth_service: AbstractAuthService = Depends(inject_auth_service(service_name))
    ):
        """需要管理员权限的端点"""
        
        # 获取当前用户
        user_data = await auth_service.get_current_user(token)
        if not user_data:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="未授权"
            )
        
        # 检查管理员权限
        has_permission = await auth_service.check_permission(
            user_id=user_data["user_id"],
            resource="admin_data",
            action="read"
        )
        
        if not has_permission:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足"
            )
        
        return {
            "message": "管理员数据",
            "user": user_data,
            "data": ["敏感数据1", "敏感数据2", "敏感数据3"]
        }
    
    # 配置信息端点
    @app.get("/config")
    async def get_config():
        """获取服务配置信息"""
        dependency_manager = get_dependency_manager(service_name)
        config = dependency_manager.get_config()
        
        # 隐藏敏感信息
        safe_config = {
            "service_name": config.get("service_name"),
            "environment": config.get("environment"),
            "debug": config.get("debug"),
            "server": config.get("server", {}),
            "logging": config.get("logging", {})
        }
        
        return safe_config
    
    return app


# 使用示例
if __name__ == "__main__":
    import uvicorn
    
    # 创建应用
    app = create_app("example-service")
    
    # 运行应用
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_level="info"
    )
